package protocol.control;

import exceptions.ArgumentException;
import protocol.Frame;

public class ReceiveInfoPacket implements Frame {

	private boolean allowed;
	private String filename;
	private int port;
	
	public boolean getAllowed() {
		return this.allowed;
	}

	public void setAllowed(boolean allowed) {
		this.allowed = allowed;
	}

	public String getFilename() {
		return this.filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public int getPort() {
		return this.port;
	}

	public void setPort(int port) throws ArgumentException {
		if (port >= 0 && port <= 65535) {
			this.port = port;
		} else {
			throw new ArgumentException("Invalid port number!");
		}
	}
	
	/**
	 * Constructor
	 */
	public ReceiveInfoPacket() {
	}
	
	/**
	 * Constructor
	 * @param bytes Supplied for the method parse()
	 */
	public ReceiveInfoPacket(byte[] bytes) {
		this.parse(bytes);
	}

	/**
	 * The defined packet format is:
	 * | 1 byte  | 255 bytes | 2 bytes |
	 * |---------|-----------|---------|
	 * | Allowed | Filename  | Port    |
	 * |---------|-----------|---------|
	 */
	public byte[] build() {
		byte[] data = new byte[258];
		/**
		 * Set the allowed field to the packet
		 * 1 = allowed, 0 = not allowed
		 */
		data[0] = (byte)(this.getAllowed() ? 1 : 0);
		/**
		 * Set the filename to the packet
		 */
		System.arraycopy(
			this.getFilename().getBytes(), 0, // source
			data, 1, // destination
			this.getFilename().getBytes().length); // copy length
		/**
		 * Set the port number to the packet
		 */
		data[256] = (byte)(this.getPort() >> 8);
		data[257] = (byte)(this.getPort() & 0xFF);
		return data;
	}

	/**
	 * The defined packet format is:
	 * | 1 byte  | 255 bytes | 2 bytes |
	 * |---------|-----------|---------|
	 * | Allowed | Filename  | Port    |
	 * |---------|-----------|---------|
	 */
	public void parse(byte[] bytes) {
		/**
		 * Save the value of the allowed field
		 */
		if (((int)bytes[0]) == 1) {
			this.setAllowed(true);
		} else {
			this.setAllowed(false);
		}
		/**
		 * Save the filename
		 */
		byte[] filename = new byte[255];
		System.arraycopy(
			bytes, 0, // source
			filename, 0, // destination
			255); // copy length
		this.setFilename(new String(filename).trim());
		/**
		 * Save the port number
		 */
		try {
			this.setPort((((int)bytes[256] & 0xFF) << 8) | ((int)bytes[257] & 0xFF));
			//this.setPort(((bytes[256] << 8) | bytes[257]));
		} catch (ArgumentException e) {
			System.err.println(e.toString());
		}
	}

}